
#import <Cocoa/Cocoa.h>

#include <Liberty3D/Engine/Window.h>

using namespace Liberty::Engine;

extern "C" id objc_retain(id);

Window::Window() : _window(nil) {
    @autoreleasepool {
        NSRect contentRect = NSMakeRect(0, 0, 1024, 768);
        
        NSWindow* window = [[NSWindow alloc] initWithContentRect:contentRect
                                                       styleMask:NSTitledWindowMask | NSClosableWindowMask | NSMiniaturizableWindowMask | NSResizableWindowMask
                                                         backing:NSBackingStoreBuffered
                                                           defer:YES];
                  
        [window setCollectionBehavior:NSWindowCollectionBehaviorFullScreenPrimary];
        _window = window;
        
        objc_retain(_window); // Work-around ARC bug... NSWindow is not retained correctly and crash the destructor if I don't do that.
    }
}

Window::~Window() {
    clean();
}

void Window::clean() {
    @autoreleasepool {
        if (_window) {
            [_window close];
            _window = nil;
        }
    }
}

void Window::show() {
    @autoreleasepool {
        [_window makeKeyAndOrderFront:NSApp];
    }
}

void Window::hide() {
    @autoreleasepool {
        [_window orderOut:NSApp];
    }
}
                   
void Window::setTitle(const std::string& s) {
    @autoreleasepool {
        [_window setTitle:[NSString stringWithUTF8String:s.c_str()]];
    }
}
